// create form objects

var cid = new Date().getTime(); // make this global
var operatorStatus;
var isTyping = 0;

// page 1

var userName = {
    xtype: "textfield",
    fieldLabel: RM.Translate.User.LiveChat.Chat.Name,
    id : "rm_pages_modules_livechat_name",
    width :400
};

var userEmail = {
    xtype: "textfield",
    fieldLabel: RM.Translate.User.LiveChat.Chat.Email,
    id : "rm_pages_modules_livechat_email",
    width : 400,
    vtype:'email'
};

var question = {
    xtype: "textarea",
    fieldLabel: RM.Translate.User.LiveChat.Chat.Question,
    id : "rm_pages_modules_livechat_question",
    width : 400
};

// this is the message panel
var messagePanel = {
    id: "rm_pages_modules_livechat_messagepanel",
    xtype: "panel",
    width: 570,
    height: 100,
    bodyStyle : "padding:10px",
    bodyBorder : false,
    border: false,
    frame : false,
    cls: "RM-LiveChat-MessageText"
};

// the sound event
var NotifySound = new Ext.ux.Media.plugin.AudioEvents({
      audioEvents :{
         beforehide : RM.RootURL+'RM/userdata/modules/LiveChat/images/bong.wav'
      },
      volume : 0.7
});

// the sound event is bound to this panel state. We hide/show the panel to trigger the sound
var NotifySoundPanel = {
    xtype: "panel",
    width: 100,
    height: 40,
    title: "",
    html: "loading...",
    id : "rm_pages_modules_livechat_sound_event_panel",
    hidden: true,
    plugins:[NotifySound]
};

// the submit button on page 1
var requestButton = {
    xtype: "button",
    text: RM.Translate.User.LiveChat.Chat.RequestButton,
    id : "rm_pages_modules_livechat_requestbutton",
    ctCls: "RM-LiveChat-RequestButton",
    handler: function(){
        // go to validation and then submit data...
        if (formValidation()){

            // if the operator is online goto the chat page

            if (operatorStatus){

                // only show the chat window if an operator is online

                ChatRequestFormPanel.hide();

                Ext.getCmp("rm_pages_modules_livechat_window").add(ChatFormPanel);
                Ext.getCmp("rm_pages_modules_livechat_window").doLayout(false,true);

                // add a startup message to the listview...
                var startmessage = {};
                startmessage.user = "Please Wait LiveChat Starting...";
                startmessage.operator = "";
                ListViewAddRow(startmessage);
            }

            this.disabled = true;
            submitForm();
        }
    }

};

// the send button on page 2
var sendButton = {
    xtype: "button",
    text: RM.Translate.User.LiveChat.Chat.SendButton,
    id : "rm_pages_modules_livechat_sendbutton",
    ctCls: "RM-LiveChat-SendButton",
    handler: function(){
        var message = RM.Pages.Functions.livechat_encode.encode(Ext.getCmp("rm_pages_modules_livechat_messagebox").getValue());
        sendMessage(message);
        Ext.getCmp("rm_pages_modules_livechat_messagebox").focus();
    }

};

function closeWindow(){
    try{
        // try closing if it's a shadowbox
        parent.Shadowbox.close();
    } catch(e){
        // if this fails try self close (works for windows)
        self.close();
    }
}

// the cancel button on page 1
var cancelButton = {
    xtype: "button",
    text: RM.Translate.User.LiveChat.Chat.CancelButton,
    id : "rm_pages_modules_livechat_cancelbutton",
    ctCls: "RM-LiveChat-CancelButton",
    handler: function(){
        closeWindow();
    }
};
// the cancel button on page 2
var cancelButton2 = {
    xtype: "button",
    text: RM.Translate.User.LiveChat.Chat.EndChatButton,
    id : "rm_pages_modules_livechat_cancelbutton2",
    ctCls: "RM-LiveChat-CancelButton2",
    handler: function(){
        // send response to server to tell admin user has left
        var request = {
            url: RM.Common.AssembleURL({
                controller : 'LiveChat',
                action: 'closechatJson',
                parameters : [{
                    name : 'chat_id',
                    value : cid
                }]
            }),
            method: 'POST',
            success: function(responseObject) {
                closeWindow();
            },
            failure: function() {
                closeWindow();
            }
        };
        var conn = new Ext.data.Connection();
        conn.request(request);
    }
};

// this is the text entry box on the chat page (2)
var ChatMessageBox = {
    xtype: "textarea",
    id : "rm_pages_modules_livechat_messagebox",
    width: 550,
    height: 50,
    cls: "RM-LiveChat-Message-Box",
    enableKeyEvents: true,
    listeners: {
        keydown: function(f, e){
            if (e.getKey() === e.ENTER) {
                var message = RM.Pages.Functions.livechat_encode.encode(this.getValue());
                sendMessage(message);
                this.focus();
                isTyping = 0;
            } else {
                // set isTyping marker
                isTyping = 1;
            }
        }
    }
};

// this is the store to hold the messages
var store = new Ext.data.JsonStore({
    fields: [
        'id','user','operator'
    ]
});

// the renderer to render the operator balloon
function operatorColumnRenderer(val){
    if (val!==""){
        var tmpl =  '<table width="280" border="0" cellpadding="0" cellspacing="0">';
            tmpl += '<tr><td class="RM-Module-LiveChat-Right-Cell-Top"></td></tr>';
            tmpl += '<tr><td class="RM-Module-LiveChat-Right-Cell-Body x-selectable"><div class="RM-Module-LiveChat-Right-Column">'+ val +'</div></td></tr>';
            tmpl += '<tr><td class="RM-Module-LiveChat-Right-Cell-Bottom"></td></tr>';
            tmpl += '</table>';
        return tmpl;
    }
}

// the renderer to render the user balloon
function userColumnRenderer(val){
    if (val!==""){
        var tmpl =  '<table width="280" border="0" cellpadding="0" cellspacing="0">';
            tmpl += '<tr><td class="RM-Module-LiveChat-Left-Cell-Top"></td></tr>';
            tmpl += '<tr><td class="RM-Module-LiveChat-Left-Cell-Body x-selectable"><div class="RM-Module-LiveChat-Left-Column">'+ val +'</div></td></tr>';
            tmpl += '<tr><td class="RM-Module-LiveChat-Left-Cell-Bottom"></td></tr>';
            tmpl += '</table>';
        return tmpl;
    }
}

// this is the chat dialogue container. We are using a grid as it easily supports scrolling to the last message added
var ChatDialogue = {
    layout: 'form',
    xtype: 'grid',
    id: "rm_pages_modules_livechat_dialogue_listview",
    store: store,
    multiSelect: true,
    columns: [{
        width: 0,
        dataIndex: 'id',
        hidden: true,
        hideable: false
    },{
        width: 295,
        dataIndex: 'user',
        renderer: userColumnRenderer
    },{
        width: 295,
        dataIndex: 'operator',
        align: 'right',
        renderer: operatorColumnRenderer
    }],
    height: 230,
    autoWidth: true,
    bodyBorder : false,
    frame : false,
    border: false
};

// this code is required to add the row to the grid...
var createRow = Ext.data.Record.create([
    {name: 'id', type: 'string'}
]);

function ListViewAddRow(data){
    if (data.user === undefined && data.operator === undefined){
        return;
    }
    var newRow = new createRow({
        id: 0,
        user: data.user,
        operator: data.operator
    });

    // add chat message to grid
    store.add(newRow);

    // trigger a sound, this panel is only used to generate an event
    Ext.getCmp("rm_pages_modules_livechat_sound_event_panel").show();
    Ext.getCmp("rm_pages_modules_livechat_sound_event_panel").hide();

    // scroll down automatically
    Ext.getCmp("rm_pages_modules_livechat_dialogue_listview").getView().focusRow(Ext.getCmp("rm_pages_modules_livechat_dialogue_listview").store.data.items.length-1);
}

// the ajax reques to get the new chat dialogue items
function getNewChatItems(){
    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'dialogueJson',
            parameters : [{
                name : 'chat_id',
                value : cid
            },{
                name: 'isTyping',
                value: isTyping
            }]
        }),
        method: 'POST',
        success: function(responseObject) {

            var jsonObject = Ext.util.JSON.decode(responseObject.responseText);

            var message = {}; // define an object to hold the message data

            // if the operator closes the chat the closed flag will be set if this is set we need to inform the user
            if (jsonObject.chatInfo[0].closed === "1"){
                message.operator = RM.Translate.User.LiveChat.Chat.OperatorNotAvailable;
                message.user = "";
                ListViewAddRow(message);
                return;
            }

            // isTyping indicator
            if (jsonObject.isTyping !== "0" ){
                Ext.getCmp("chat_toolbar").setText(RM.Translate.User.LiveChat.Chat.OperatorTyping);
            } else {
                Ext.getCmp("chat_toolbar").setText("");
            }

            if (jsonObject.data.length !== 0 ){

                var i = 0;for(i; i < jsonObject.data.length; i++){
                    // add each message to the window
                    if (jsonObject.data[i].operator!=="") {message.operator = RM.Pages.Functions.livechat_encode.decode(jsonObject.data[i].operator);} else {message.operator="";}
                    if (jsonObject.data[i].user!=="") {message.user = RM.Pages.Functions.livechat_encode.decode(jsonObject.data[i].user);} else {message.user = "";}
                    ListViewAddRow(message);
                }

            }

            Ext.getCmp('rm_pages_modules_livechat_messagebox').focus();
            setTimeout(function(){
                Ext.getCmp('rm_pages_modules_livechat_messagebox').focus();
                getNewChatItems();
            }, 2000);

        },
        failure: function() {
            // reschedule the next collection, for 10 seconds
            setTimeout(function(){
                Ext.getCmp('rm_pages_modules_livechat_messagebox').focus();
                getNewChatItems();
            }, 10000);
        }
    };

    Ext.getCmp('rm_pages_modules_livechat_messagebox').focus();
    var conn = new Ext.data.Connection();
    conn.request(request);
    isTyping = 0;

}

// the holding panel for the items on page 1
var ChatRequestFormPanel = new Ext.FormPanel({
    id : 'rm_pages_modules_livechat_request_form',
    title: RM.Translate.User.LiveChat.Chat.RequestFormTitle,
    bodyStyle : "padding:10px;",
    height: 350,
    items: [
        messagePanel,
        userName,
        userEmail,
        question,
        requestButton,
        cancelButton
    ],
    bbar: new Ext.ux.StatusBar({
        id: 'request_toolbar',
        items: []
    })
});

// sets the status bar
var requestStatusBar = Ext.getCmp('request_toolbar');
requestStatusBar.setStatus({
    text: "Powered by <strong><span style='color: #FF6600'>Res</span>Mania</strong> (LiveChat Module)"
});

// the holding panel for the chat page (page2)
var ChatFormPanel = {
    xtype : "panel",
    layout: 'form',
    id : 'rm_pages_modules_livechat_chat_form',
    title: RM.Translate.User.LiveChat.Chat.LiveChat,
    items : [
        ChatDialogue,
        ChatMessageBox,
        NotifySoundPanel,
        sendButton

    ],
    height: 350,
    bbar: new Ext.ux.StatusBar({
        id: 'chat_toolbar',
        items: [
            cancelButton2
        ]
    })
};

// The ajax call to check if the operator is available
function checkOperatorAvailable(){

    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'checkavailableJson'
        }),
        method: 'POST',
        success: function(responseObject) {
            var jsonObject = Ext.util.JSON.decode(responseObject.responseText);

            if (jsonObject.operator_online){
                operatorStatus = true;
                Ext.getCmp("rm_pages_modules_livechat_messagepanel").update(RM.Translate.User.LiveChat.Chat.OnlineMessage);
            } else {
                operatorStatus = false;
                Ext.getCmp("rm_pages_modules_livechat_messagepanel").update(RM.Translate.User.LiveChat.Chat.OfflineMessage);
            }
        },
        failure: function() {
            Ext.Msg.alert('Status', RM.Translate.Common.UnableToShow);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
}

// basic validation
function formValidation(){

    if (Ext.getCmp("rm_pages_modules_livechat_name").value==="") {return false;}
    if (Ext.getCmp("rm_pages_modules_livechat_email").value==="") {return false;}

    return true;
}

// submits page 1 for action
function submitForm(){

    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'requestchatJson',
            parameters : [{
                name : 'name',
                value : Ext.getCmp("rm_pages_modules_livechat_name").getValue()
            }, {
                name : 'email',
                value : Ext.getCmp("rm_pages_modules_livechat_email").getValue()
            },{
                name : 'question',
                value : Ext.getCmp("rm_pages_modules_livechat_question").getValue()
            },{
                name : 'ip',
                value : user_ip
            },{
                name : 'chat_id',
                value : cid
            },{
                name: 'operatorStatus',
                value: operatorStatus
            }]
        }),
        method: 'POST',
        success: function(responseObject) {

            var jsonObject = Ext.util.JSON.decode(responseObject.responseText);

            if (operatorStatus && jsonObject.data.success){
                // if the operatoris Online and the chat has started
                setTimeout(function(){
                    getNewChatItems();
                }, 4000);
            }

            if (!operatorStatus && jsonObject.data.success){
                // if the operator is offline and the email has been sent
                Ext.getCmp("rm_pages_modules_livechat_messagepanel").update(RM.Translate.User.LiveChat.Chat.MessageSent);

            }


        },
        failure: function() {
            Ext.Msg.alert('Status', RM.Translate.Common.UnableToShow);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
}

// send the text message
function sendMessage(messageString){
    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'sendmessageJson'
        }),
        params : {
                'chat_id': cid,
                'message': messageString,
                'timestamp': new Date().getTime()
        },
        method: 'post',
        success: function(responseObject) {

            Ext.getCmp('rm_pages_modules_livechat_messagebox').setValue("");

        },
        failure: function() {
            Ext.Msg.alert('Status', RM.Translate.Common.UnableToShow);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
}

// the caller to render everything when Ext is ready
Ext.onReady(function(){

    Ext.QuickTips.init();

    var loadingmessage = document.getElementById('loadingmessage');
    loadingmessage.style.visibility = 'hidden';
    loadingmessage.style.display = "none";


    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'under';

     new Ext.Panel({
            id: "rm_pages_modules_livechat_window",
            renderTo: "chatform",
            width:620,
            height:350,
            items: [
                ChatRequestFormPanel
            ]
     });

     checkOperatorAvailable();

     try{
         Ext.getCmp('rm_pages_modules_livechat_messagebox').setValue(RM.Translate.User.LiveChat.Chat.EnterMessageHere);
     } catch (err){
         // this is required as the object may not exist so we use this to supress the error
     }
});